<?php

/**
 * @Author: wuchenge
 * @Date: 2020-11-30 15:14:49
 * @email: ligui0506@sina.com
 * @descript: 项目 token 加解密
 */

namespace App\Libraries;

use App\Models\Admin;
use App\Models\Token as TokenModel;

class Token
{
    /**
     * 生成Token
     *
     * @param  array  $payload  载荷
     * @return string
     */
    public static function createToken(array $payload = [])
    {
        $config  = config('api.jwt');
        $payload = array_merge([
            'iss' => $config['issuer'],
            'iat' => $_SERVER['REQUEST_TIME'],
            'exp' => $_SERVER['REQUEST_TIME'] + $config['expire'],
        ], $payload);

        return JWT::encode($payload, $config['key'], $config['algorithm']);
    }

    /**
     * 前台还是后台
     * @param  [type] $model [description]
     * @return [type]        [description]
     */
    public static function authToken($model)
    {
        $payload = self::verifyToken();

        if (!$payload) {
            return false;
        }

        // 用户
        $user = $model::find($payload['id']);

        if (!$user) {
            return false;
        }

        $versions = TokenModel::where('accountable_id', $payload['id'])
            ->where('type', $payload['type'])
            ->where('accountable_type', $model)
            ->first();

        if (!$versions) {
            return false;
        }

        if ($versions->version != $payload['version']) {
            return false;
        }

        $user->login_type = $payload['type'];
        return $user;
    }

    /**
     * 验证Token
     */
    public static function verifyToken($token = '')
    {
        $config = config('api.jwt');

        if (empty($token)) {
            $token = self::getToken();
        }

        if (empty($token)) {
            return false;
        }

        return JWT::decode($token, $config['key']);
    }

    /**
     * 获取token
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public static function getToken()
    {
        if (array_key_exists('HTTP_AUTHORIZATION', $_SERVER)) {
            return $_SERVER['HTTP_AUTHORIZATION'];
        }

        if (array_key_exists('token', $_POST)) {
            return $_POST['token'];
        }

        return '';
    }
}
